<?php

namespace backend\models;

use Yii;
use yii\helpers\ArrayHelper;
use kartik\builder\TabularForm;
use kartik\grid\GridView;


/**
 * This is the model class for table "customer_contact".
 *
 * @property string $id
 * @property string $contact
 * @property string $post
 * @property string $mobile
 * @property string $image
 * @property string $created_at
 * @property integer $customer_id
 */
class CustomerContact extends \yii\db\ActiveRecord
{
    public static function getDb()
    {
        return Yii::$app->get('forge');
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'customer_contact';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
//            [['contact', 'post', 'mobile'], 'required'],
            [['created_at', 'owner'], 'safe'],
//            [['mobile'], 'unique', 'message' => '已存在'],
            [['image'], 'default', 'value' => ''],
            [['contact', 'post', 'mobile', 'image'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'contact' => '联系人',
            'post' => '职务',
            'mobile' => '电话',
            'image' => '名片',
            'created_at' => '创建时间',
        ];
    }

    public function getFormAttributes()
    {
        return [
            'id' => [ // primary key attribute
                'type' => TabularForm::INPUT_HIDDEN,
                'columnOptions' => ['hidden' => true]
            ],
            'contact' => ['type' => TabularForm::INPUT_TEXT],
            'post' => ['type' => TabularForm::INPUT_TEXT],
            'mobile' => ['type' => TabularForm::INPUT_TEXT],
            'image' => ['type' => TabularForm::INPUT_TEXT],
        ];
    }

    /**
     * @inheritdoc
     * @return CustomerContactQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new CustomerContactQuery(get_called_class());
    }

    public static function findByMobile($mobile)
    {
        return static::findOne(['mobile' => $mobile]);
    }

    public function getBackendUser()
    {
        return $this->hasOne(User::className(), ['id' => 'owner']);
    }

    public function validateMobileUnique($mobile)
    {
        if ($contact = CustomerContact::findOne(['mobile' => $mobile])) {
            return $contact;
        } else {
            return false;
        }
    }
}
